package framework.webclient;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

import org.openems.entity.Entity;

public class EntityQueue {
	private BlockingQueue<Entity> queue = new LinkedBlockingQueue<Entity>(); 
	private HttpEntitySocket socket;
	
	public EntityQueue(final HttpEntitySocket sock) {
		this.socket = sock;
		
		new Thread() {

			@Override
			public void run() {
				while(true) {
					try {
						List<Entity> entities = new ArrayList<Entity>();
						entities.add(queue.take());
						queue.drainTo(entities);
						//Entity entity = queue.take();
						entities = eliminate(entities);
						socket.upload(entities);
						System.out.println("Uploading... "  + entities);
						Thread.sleep(1000);
					}
					catch (Exception e) {
						e.printStackTrace();
					}
					//System.out.println("Uploading... "  + entity.getName());
				}
			}
			private List<Entity> eliminate(List<Entity> entities) {
				List<Entity> ret = new ArrayList<Entity>();
				Set<String> set = new HashSet<String>();
				for (Entity entity : entities) {
					if (!set.contains(entity.getKey().toString())) {
						set.add(entity.getKey().toString());
						ret.add(entity);
					}
				}
				return ret;
			}
		}.start();
	}
	
	public void addEntity(Entity entity) {
		this.queue.add(entity);
	}
	
}
